import { Injectable } from '@nestjs/common';
import { InjectRedis } from '@nestjs-modules/ioredis';
import Redis from 'ioredis';

export const ARTICLE_BROWSER = `article:view:`

@Injectable()
export class RedisService {
  constructor(
    @InjectRedis() private readonly redis: Redis
  ) {}

  set(key: string, value: any) {
    return this.redis.set(process.env.REDIS_PREFIX + key, value);
  }

  get(key: string): any {
    return this.redis.get(process.env.REDIS_PREFIX + key);
  }

  async getAllWithPrefix(prefix: string): Promise<Map<string, any>> {
    const pattern = `${process.env.REDIS_PREFIX}${prefix}*`;
    const keysMap = new Map<string, any>();

    return new Promise((resolve, reject) => {
      this.redis.scanStream({
        match: pattern,
      })
        .on('data', async (keys) => {
          const promises = keys.map(async (key) => {
            const value = await this.redis.get(key);
            keysMap.set(key.replace(process.env.REDIS_PREFIX, ''), value); // 移除前缀再存入map
          });
          await Promise.all(promises);
        })
        .on('end', () => resolve(keysMap))
        .on('error', (error) => reject(error));
    });
  }
}
